//
//  CNUserAccountViewModel.swift
//  Ccweibo
//
//  Created by 陈锦聪 on 16/3/23.
//  Copyright © 2016年 Coco. All rights reserved.
//

import UIKit

class CNUserAccountViewModel: NSObject {
    
    static let sharedInstance: CNUserAccountViewModel = CNUserAccountViewModel()
    
    private override init() {
        super.init()
        // 从沙盒加载用户账户信息
        userAccount = loadUserAccount()
    }
    // 用户账户信息归档目录
    private let documentPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last!.stringByAppendingString("/account.plist")
    
    /// 用户账户信息
    var userAccount: CNUserAccount?
    
    /// 用户是否登陆
    var isLogin: Bool {
        get {
            return userAccount != nil
        }
    }
    
    func loadUserInfo(completion: (error: NSError?) -> ()) {
        
        let urlString = "2/users/show.json"
        
        let parameters = ["uid" : userAccount!.uid!]
        CNNetworkTool.sharedInstance.sendGetRequest(urlString, parameters: parameters) { (result, error) -> () in
            if error != nil {
                completion(error: error)
            } else {
                self.userAccount?.screen_name = result?["screen_name"] as? String
                self.userAccount?.avatar_large = result?["avatar_large"] as? String
                self.saveUserAccount()
                completion(error: nil)
            }
        }
    }

    // 加载access_Token
    func loadAccessToken(code: String, completion: (error: NSError?)->()) {
        
        let urlString = "oauth2/access_token"
        
        let parameters = [
            "client_id" : client_id,
            "client_secret" : client_secret,
            "grant_type" : grant_type,
            "code" : code,
            "redirect_uri" : redirect_uri
        ]
        CNNetworkTool.sharedInstance.sendPostRequest(urlString, parameters: parameters) { (result, error) -> () in
            if error != nil {
                completion(error: error)
            } else {
                self.userAccount = CNUserAccount(dict: result!)
                self.saveUserAccount()
                completion(error: nil)
            }
        }
    }
    
    // 保存用户账户
    private func saveUserAccount() {
        if userAccount != nil {
//            print("documentPath:\(documentPath)")
            NSKeyedArchiver.archiveRootObject(userAccount!, toFile: documentPath)
        }
    }
    
    // 加载用户账户
    private func loadUserAccount() -> CNUserAccount? {
        let account = NSKeyedUnarchiver.unarchiveObjectWithFile(documentPath) as? CNUserAccount
//        account?.expiresDate = NSDate(timeIntervalSinceNow: -1000)
        if account != nil && account?.expiresDate?.compare(NSDate()) == NSComparisonResult.OrderedDescending {
//            print("account:\(account)")
            return account
        }
        return nil
    }
}
